<template>
  <div class="product_area">
    <!-- t头部查询 -->
    <div class="header">
      <div class="tab">
        <div class="tab_left">
          <el-icon> <Search /> </el-icon>
          筛选搜索
        </div>
        <div class="tab_right">
          <el-button @click="reset1">重置</el-button>
          <el-button type="primary" @click="searchHandle(form)"
            >查询结果</el-button
          >
        </div>
      </div>
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input v-model="form.keyword" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品货号">
          <el-input placeholder="请输入商品货号" v-model="form.productSn" />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader
            v-model="cage"
            :options="CategoryList"
            placeholder="请选择商品分类"
            @change="cascader"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="商品品牌">
          <el-select
            placeholder="请选择商品品牌"
            clearable
            v-model="form.brandId"
          >
            <el-option
              v-for="(item, index) in productBrand"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select
            placeholder="请选择上架状态"
            clearable
            v-model="form.publishStatus"
          >
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            placeholder="请选择审核状态"
            clearable
            v-model="form.verifyStatus"
          >
            <el-option label="审核通过" :value="1" />
            <el-option label="审核中" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <!-- 添加 -->
    <div class="list">
      <div class="list_left">
        <el-icon><Tickets /></el-icon>
        数据列表
      </div>
      <div class="list_right">
        <el-button
          v-permission="'addProduct'"
          @click="router.push('/pms/addProduct')"
          >添加</el-button
        >
      </div>
    </div>
    <!-- 表格 -->
    <el-table
      :data="list"
      border
      style="width: 100%"
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" />
      <el-table-column align="center" prop="id" label="编号" />
      <el-table-column align="center" label="商品图片">
        <template #default="{ row }">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.pic"
            fit="fill"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品名称">
        <template #default="{ row }">
          <div>{{ row.name }}</div>
          <div>品牌:{{ row.brandName }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="价格/货号">
        <template #default="{ row }">
          <div>价格：{{ row.price }}</div>
          <div>货号：{{ row.productSn }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="标签">
        <template #default="{ row }">
          <div>
            上架：
            <el-switch
              :model-value="row.publishStatus"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus(row, 'publishStatus')"
            />
          </div>
          <div>
            新品：
            <el-switch
              :model-value="row.newStatus"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus(row, 'newStatus')"
            />
          </div>
          <div>
            推荐：
            <el-switch
              :model-value="row.recommandStatus"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus(row, 'recommandStatus')"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="sort" label="排序" />
      <el-table-column align="center" label="SKU库存">
        <el-button @click="isShow = true" type="primary" :icon="EditPen" />
      </el-table-column>

      <el-table-column align="center" prop="sale" label="销量" />
      <el-table-column align="center" prop="date" label="审核状态">
        未审核 <br />
        <el-button type="primary" link>审核详情</el-button>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button-group>
            <div class="btn">
              <el-button
                v-permission="'updateProduct'"
                @click="router.push(`/pms/addProduct?id=${row.id}`)"
                >编辑</el-button
              >
              <el-button type="danger" @click="Delete(row)"> 删除 </el-button>
            </div>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <div class="more">
        <el-select v-model="seleteItem" placeholder="批量操作">
          <el-option
            v-for="(item, index) in seletes"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="doMore">确定</el-button>
      </div>
      <ElConfigProvider :locale="zhCn">
        <el-pagination
          v-model:current-page="form.pageNum"
          v-model:page-size="form.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="pageChangeHandle(form)"
          @current-change="pageSizeChangeHandle(form)"
        />
      </ElConfigProvider>
    </div>
  </div>
  <SKUVue :isShow="isShow" @hide="hide" />
</template>
<script setup lang="ts">
import {
  getProductListAPI,
  getProductListByNameAPI,
  productCategoryListApi,
  withChildrenApi,
  getBrandListAllApi,
  updateNewStatusAPI,
  updatePudeleteStatusblishStatusAPI,
  updateRecommendStatusAPI,
  deleteStatusAPI,
} from "./api";
import {
  ElConfigProvider,
  ElMessage,
  ElMessageBox,
  ElTable,
} from "element-plus";
import { Search, Tickets, EditPen } from "@element-plus/icons-vue";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { ApiAddCoupon } from "../sms/api";
import useTable from "@/hooks/tableData";
import SKUVue from "../ums/SKU.vue";
import { ref } from "vue";
import { useRouter } from "vue-router";

// 路由
const router = useRouter();

// table  dom
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// const toggleSelection = (rows?: IProductModel[]) => {
//   if (rows) {
//     rows.forEach((row) => {
//       // TODO: improvement typing when refactor table
//       // eslint-disable-next-line @typescript-eslint/ban-ts-comment
//       // @ts-expect-error
//       multipleTableRef.value!.toggleRowSelection(row, undefined);
//     });
//   } else {
//     multipleTableRef.value!.clearSelection();
//   }
// };
const multipleSelection = ref<IProductModel[]>([]);
const handleSelectionChange = (val: IProductModel[]) => {
  multipleSelection.value = val;
};

// 批量操作selete
const seletes = ref([
  { label: "商品上架", value: "productPush" },
  { label: "商品下架", value: "productPull" },
  { label: "设为推荐", value: "setReCommand" },
  { label: "取消推荐", value: "cancelReCommand" },
  { label: "设为新品", value: "setNew" },
  { label: "取消新品", value: "cancelNew" },
  { label: "转移到分类", value: "moveCagete" },
  { label: "移回回收站", value: "moveDelate" },
]);

// 绑定得value
const seleteItem = ref();

// 控制SKU显隐
const isShow = ref(false);

const hide = () => {
  isShow.value = false;
};

// 删除
const Delete = (row: IProductModel) => {
  deleteStatusAPI(1, row.id).then((res) => {
    if (res.code == 200) {
      searchHandle(form.value);
      ElMessage.success("删除成功");
    }
  });
};

//批量操作
const doMore = () => {
  if (multipleSelection.value.length > 0 && seleteItem.value) {
    let ids = multipleSelection.value.map((item) => item.id).join(",");

    if (seleteItem.value == "productPush") {
      updatePudeleteStatusblishStatusAPI(ids, 1).then((res) => {
        if (res.code == 200) ElMessage.success("修改成功");
      });
    } else if (seleteItem.value == "productPull") {
      updatePudeleteStatusblishStatusAPI(ids, 0).then((res) => {
        if (res.code == 200) ElMessage.success("修改成功");
      });
    } else if (seleteItem.value == "setReCommand") {
      updateRecommendStatusAPI(ids, 1).then((res) => {
        if (res.code == 200) ElMessage.success("修改成功");
      });
    } else if (seleteItem.value == "cancelReCommand") {
      updateRecommendStatusAPI(ids, 0).then((res) => {
        if (res.code == 200) ElMessage.success("修改成功");
      });
    } else if (seleteItem.value == "setNew") {
      updateNewStatusAPI(ids, 1).then((res) => {
        if (res.code == 200) ElMessage.success("修改成功");
      });
    } else if (seleteItem.value == "cancelNew") {
      updateNewStatusAPI(ids, 0).then((res) => {
        if (res.code == 200) ElMessage.success("修改成功");
      });
    } else if (seleteItem.value == "moveCagete") {
      // updateNewStatusAPI(ids, 0).then(res => {
      //   if(res.code==200)ElMessage.success('修改成功')
      // })
      reset(form.value);
    } else {
      deleteStatusAPI(1, ids).then((res) => {
        if (res.code == 200) ElMessage.success("修改成功");
      });
    }
    searchHandle(form.value);
    seleteItem.value = "";
  } else {
    ElMessage.warning("清选择");
  }
};
// 商品分类请求
withChildrenApi().then((res) => {
  if (res.code !== 200) return;
  CategoryList.value = res.data.map((item) => ({
    value: item.id,
    label: item.name,
    children: item.children.map((item) => ({
      value: item.id,
      label: item.name,
    })),
  }));
});

// 搜索初始数据
const form = ref<IProductParams>({
  // 商品品牌编号
  // brandId: 0,
  // 商品名称模糊关键字
  keyword: "",
  pageNum: 1,
  pageSize: 10,
  // 商品分类编号
  // productCategoryId: 0,
  // 商品货号
  // productSn: "",
  // 上架状态
  // publishStatus: 0,
  // 审核状态
  // verifyStatus: 0,
});

// 改变状态
const changeStatus = (row: IProductModel, type: string) => {
  if (type == "newStatus") {
    row.newStatus = row.newStatus == 1 ? 0 : 1;
    updateNewStatusAPI(row.id, row.newStatus).then((res) => {
      if (res.code == 200) {
        ElMessage.success("修改成功");
      } else {
        row.newStatus = row.newStatus == 1 ? 1 : 0;
      }
    });
  } else if (type == "publishStatus") {
    row.publishStatus = row.publishStatus == 1 ? 0 : 1;
    updatePudeleteStatusblishStatusAPI(row.id, row.publishStatus).then(
      (res) => {
        if (res.code == 200) {
          ElMessage.success("修改成功");
        } else {
          row.publishStatus = row.publishStatus == 1 ? 1 : 0;
        }
      }
    );
  } else {
    row.recommandStatus = row.recommandStatus == 1 ? 0 : 1;

    updateRecommendStatusAPI(row.id, row.recommandStatus).then((res) => {
      if (res.code == 200) {
        ElMessage.success("修改成功");
      } else {
        row.recommandStatus = row.recommandStatus == 1 ? 1 : 0;
      }
    });
  }
};

// 商品分类数据
const CategoryList = ref<
  {
    value: number;
    label: string;
    children: { value: number; label: string }[];
  }[]
>([]);

// c处理多级数据
const cascader = () => {
  if (cage.value)
    form.value.productCategoryId = cage.value[cage.value.length - 1] + "";
};

const cage = ref<number[]>([]);

// 商品品牌数据
const productBrand = ref();

// 商品品牌管理请求
getBrandListAllApi().then((res) => {
  productBrand.value = res.data;
});

// 重置
const reset1 = () => {
  form.value = { keyword: "" };

  cage.value = [];
  reset(form.value);
};

// 表单数据及方法
const {
  list,
  pageNum,
  pageSize,
  total,
  pageChangeHandle,
  pageSizeChangeHandle,
  searchHandle,
  reset,
} = useTable(getProductListAPI, form.value);
</script>
<style lang="less" scoped>
.product_area {
  .header {
    padding: 20px;
    box-sizing: border-box;
    margin-bottom: 20px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.03),
      0px 0px 80px rgba(0, 0, 0, 0.06);
    .tab {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    .el-form {
      display: grid;
      grid-template-columns: repeat(3, 33%);
      margin-left: 100px;
      .el-input {
        width: 215px;
      }
    }
  }
  .list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.03),
      0px 0px 80px rgba(0, 0, 0, 0.06);
    margin-bottom: 20px;
    padding: 20px;
  }
  .btn {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: start;
    width: 60px;
    .el-button {
      margin-left: 0px;
    }
  }
  .pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
    .el-button {
      margin-left: 20px;
    }
  }
}
</style>
